
// posix header
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>

#include <iterator>

// openMP header
#include <omp.h>

// c++ header
#include <fstream>
#include <iostream>
#include <regex>
#include <sstream>
#include <stdexcept>
#include <thread>
#include <vector>

using namespace std;

const string one_dot(".");
const string tow_dot("..");

void process_dataset(string input_path, string output_file) {
  // check if the file exists
  DIR* dataset_dir_open;
  if ((dataset_dir_open = opendir(input_path.c_str())) == NULL) {
    cout << "in valid dataset dir:" << input_path << endl;
    std::abort();
  }

  ofstream ofs;
  ofs.open(output_file);

  struct dirent* dir_open;

  while ((dir_open = readdir(dataset_dir_open)) != NULL) {  //遍历
    if (dir_open->d_type == DT_REG && dir_open->d_name != one_dot &&
        dir_open->d_name != tow_dot) {
      auto input_file = input_path + "/" + dir_open->d_name;
      cout << "start to read " << input_file << "..." << endl;

      std::ifstream ifs(input_file);

      std::istreambuf_iterator<char> file_begin(ifs);
      std::istreambuf_iterator<char> file_end;
      std::string file_data(file_begin, file_end);

      cout << "success to read " << input_file << "..." << endl;

      auto len = file_data.size();

      if (file_data[len - 1] != '\n') {
        file_data += "\n";
      }

      ofs << file_data;

    } else if (dir_open->d_name != one_dot && dir_open->d_name != tow_dot) {
      cout << "Error 1st level directory..." << endl;
      std::abort();
    }
  }

  ofs.close();
}

int main(int argc, char* argv[]) {
  if (argc < 2) {
    cout << "Enter the base directory..." << endl;
    std::abort();
  }

  /* 输入、输出文件夹 */
  string dataset_path = argv[1];

  int len = dataset_path.size();

  string output_file;

  if (dataset_path[len - 1] == '/') {
    output_file = dataset_path.substr(0, len - 1) + "_result.txt";
  } else {
    output_file = dataset_path + "_result.txt";
  }

  process_dataset(dataset_path, output_file);

  return 0;
}
